<!--  -->
<template>
    <div class="bg-gradient-to-br from-gray-600 to-black">
        <div data-tauri-drag-region class="titlebar">
            <div data-tauri-drag-region style="
          margin-right: auto;
          display: inline-flex;
          justify-content: center;
          align-items: center;
          margin-left: 10px;
          font-size: 10pt;
        ">

            </div>
            <div class="titlebar-button" id="titlebar-minimize">
                <el-icon>
                    <Minus />
                </el-icon>
            </div>
            <div class="titlebar-button" id="titlebar-maximize">
                <el-icon>
                    <Plus />
                </el-icon>
            </div>
            <div class="titlebar-button" id="titlebar-close">
                <el-icon>
                    <Close />
                </el-icon>
            </div>
        </div>

        <div id="myTargetElement" ref="myTargetElement" style="height: 580px;overflow: auto;font-size: 14px;"
            class="p-4 mt-8">
            <!-- Chat Container -->
            <div class="pr-4 h-[400px]" style="min-width: 100%; ">

                <el-row v-for="(o, i) in info" v-bind:key="i" v-show="o.role != 'system'" class="mt-4">
                    <el-col :span="4">
                        <div class="text-center mt-2 p-1">
                            <el-avatar :src="getrole(o.role, 3)" />
                            <el-tag effect="dark" :type="getrole(o.role, 2)" round>{{ getrole(o.role, 1) }}</el-tag>
                        </div>
                    </el-col>
                    <el-col :span="20" style="box-shadow: 2px 2px 4px #fff;border-radius: 8px;padding: 5px;">
                        <div class="leading-relaxed">

                            <div v-html="getMdiText(o.content)" class="p-2 pl-2"> </div>
                        </div>
                    </el-col>
                    <!-- <el-divider /> -->
                </el-row>
            </div>
            <!-- Input box  -->
            <div style="height: 10px;"></div>



        </div>
    </div>
</template>

<script>
import { appWindow, WebviewWindow, LogicalSize } from "@tauri-apps/api/window";
import { emit, listen } from '@tauri-apps/api/event'
import { getClient, ResponseType } from '@tauri-apps/api/http';
import MarkdownIt from 'markdown-it'
import mdKatex from '@traptitech/markdown-it-katex'
import hljs from 'highlight.js';
import "highlight.js/styles/atom-one-dark.min.css";
import localforage from 'localforage';
import { _, forEach } from "lodash";
const mdi = new MarkdownIt({
    linkify: true,
    highlight(code, language) {
        const validLang = !!(language && hljs.getLanguage(language))
        if (validLang) {
            const lang = language ?? ''
            return highlightBlock(hljs.highlight(lang, code, true).value, lang)
        }
        return highlightBlock(hljs.highlightAuto(code).value, '')
    }
}).use(mdKatex, { blockClass: 'katexmath-block rounded-md p-[10px]', errorColor: ' #cc0000' })
function generateRandomPassword(length) {
    var result = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    var charactersLength = characters.length;

    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}

function highlightBlock(str, lang) {
    // Removed the inline onclick attribute
    var id = generateRandomPassword(8);
    return `<pre class="pre-code-box mt-1 mb-1"><div class="pre-code-header" style="text-align: right;"><span class="code-block-header__lang text-red-500">[${lang}]</span><button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-2 rounded"  onClick="copyCode('${id}')">复制代码</button></div><div class="pre-code"><code id="${id}" class="hljs code-block-body ${lang}">${str}</code></div></pre>`;
}
export default {
    data() {
        return {
            info: [],

        };
    },

    components: {},

    computed: {},

    mounted() {

        document
            .getElementById("titlebar-minimize")
            .addEventListener("click", () => appWindow.minimize());
        document
            .getElementById("titlebar-maximize")
            .addEventListener("click", () => appWindow.toggleMaximize());
        document
            .getElementById("titlebar-close")
            .addEventListener("click", () => appWindow.close());

        this.init();

    },

    created() { },

    methods: {


        getrole(role, type) {
            if (type == 1) {
                if (role == 'system') {
                    return '系统设定';
                }
                else if (role == 'user') {
                    return '我';
                }
                else if (role == 'assistant') {
                    return 'Ewked';
                }
            }
            else if (type == 2) {
                if (role == 'system') {
                    return 'warning';
                }
                else if (role == 'user') {
                    return 'info';
                }
                else if (role == 'assistant') {
                    return 'success';
                }
            }
            else if (type == 3) {
                if (role == 'system') {
                    return 'warning';
                }
                else if (role == 'user') {
                    return 'https://zt-1304966785.cos.ap-nanjing.myqcloud.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20231230001143-removebg%20%281%29.png';
                }
                else if (role == 'assistant') {
                    return 'https://zt-1304966785.cos.ap-nanjing.myqcloud.com/65194888-78cb-4da0-a4d3-7465876675dc.jpg';

                }
            }
        },
        getMdiText(value) {
            return mdi.render(value)
        },
        getText(str) {
            // 在两个 ··· 之间提取的正则表达式
            const regex = /```(.*?)```/g;

            // 提取字符串并进行处理
            const extractedText = str.replace(regex, (match, group) => {
                // 使用 getMdiText 方法对提取的字符串进行处理
                const processedText = this.getMdiText(group);
                // 返回处理后的字符串
                return processedText;
            });

            return extractedText;
        },

        async init() {
            try {
                const value = await localforage.getItem('info');

                this.info = JSON.parse(value);

            } catch (err) {
                // 处理错误
                console.error(err);
            }

            listen("gpt", (event) => {
                console.log('event', event)
                this.info = event.payload;
                // this.info = _.unionBy(this.info, event.payload, 'content');
                this.scrollToBottom();

            });
            listen("done", (event) => {

                console.log('done:')
                const serializableData = JSON.stringify(this.info);
                localforage.setItem('info', serializableData).then(function (value) {
                    // 当值被存储后执行
                    console.log(value);
                }).catch(function (err) {
                    // 处理错误
                });
            });
        },
        removeDuplicatesFromT(info) {
            return info.map(item => {
                if (item.t) {
                    // 创建一个 Set 来存储所有不重复的字符
                    const uniqueChars = new Set(item.t);
                    // 将 Set 转换回字符串
                    item.t = Array.from(uniqueChars).join('');
                }
                return item;
            });
        },
        scrollToBottom: function () {
            // 获取你希望滚动到的元素。例如，滚动到具有特定ref的元素

            let scroll_to_bottom = document.getElementById('myTargetElement');
            scroll_to_bottom.scrollTop = scroll_to_bottom.scrollHeight;
        },
    }
}

</script>
<style lang='scss' scoped>
.is-top {
    color: #fff !important
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.circle-image2 {
    position: absolute;
    top: 5%;
    /* 调整位置使图片居中 */
    left: 5%;
    width: 90%;
    /* 减小图片大小 */
    height: 90%;

    border-radius: 50%;
}

.circle-image2::before {
    content: '';
    position: absolute;
    top: 5%;
    /* 调整位置使图片居中 */
    left: 5%;
    width: 90%;
    /* 减小图片大小 */
    height: 90%;
    background-image: url('https://zt-1304966785.cos.ap-nanjing.myqcloud.com/65194888-78cb-4da0-a4d3-7465876675dc.jpg');

    background-size: 100% 100%;
    border-radius: 50%;
    z-index: 2;
    border: 0px #240229 solid;

    /* 确保图片在最上层 */
}

.circle-image2 span {
    position: absolute;
    top: 0%;
    /* 调整位置使图片居中 */
    left: 0%;
    width: 100%;
    /* 减小图片大小 */
    height: 100%;
    border-radius: 50%;
    background: linear-gradient(#FF0000, #FFA500, #FFFF00, #00FF00, #00FFFF, #0000FF, #800080);
    filter: blur(15px);
    animation: r 5s linear infinite;
    z-index: 1;
}


.circle-image3 {
    position: absolute;
    top: 5%;
    /* 调整位置使图片居中 */
    left: 5%;
    width: 90%;
    /* 减小图片大小 */
    height: 90%;

    border-radius: 50%;
}

.circle-image3::before {
    content: '';
    position: absolute;
    top: 5%;
    /* 调整位置使图片居中 */
    left: 5%;
    width: 90%;
    /* 减小图片大小 */
    height: 90%;
    background-image: url('https://zt-1304966785.cos.ap-nanjing.myqcloud.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20231230001143-removebg%20%281%29.png');

    background-size: 100% 100%;
    border-radius: 50%;
    z-index: 2;
    border: 0px #240229 solid;

    /* 确保图片在最上层 */
}

.circle-image3 span {
    position: absolute;
    top: 0%;
    /* 调整位置使图片居中 */
    left: 0%;
    width: 100%;
    /* 减小图片大小 */
    height: 100%;
    border-radius: 50%;
    background: linear-gradient(#FF0000, #FFA500, #FFFF00, #00FF00, #00FFFF, #0000FF, #800080);
    filter: blur(15px);
    animation: r 5s linear infinite;
    z-index: 1;
}

@keyframes r {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}
</style>